import React from 'react';
import PropTypes from 'prop-types';
import {Spin, Form, Card, Button, Row, Col, Table} from 'antd';
import {FORM_OPTIONS, TABLE, PAGE} from '../constants';
import TextArea from 'Shared/components/TextArea';
import {conventEnumValueToString} from '../utils';
import {agentKind, saleOrderBusinessType} from '../Enum';
import {hasPermissions} from './utils';
import {PERMISSION} from './constants';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import styles from './style.css';
import routes from './routes';
const {Description} = DescriptionList;
const FormItem = Form.Item;

export class DetailPanel extends React.PureComponent {
    state = {
        loading: false,
        detailPagination: {
            pageIndex: PAGE.index,
            pageSize: 10,
            sortedColumnKey: 'code',
            sortedOrder: true,
        },
        newDealerResourceLists: [],
        lv2: [],
        lv3: [],
        lv4: [],
        isSearch: false,
    };
    componentDidMount() {
        this.props.init();
    }
    handleUpdateClick = () => {
        this.props.history.push(routes.update.format(this.props.id));
    }
    onChangeDetail = (pagination, filters, sorter) => {
        this.setState({
            detailPagination: {
                pageIndex: pagination.current - 1,
                pageSize: pagination.pageSize,
                sortedColumnKey: sorter.columnKey,
                sortedOrder: sorter.order,
            }
        });
    };
    onSearch = () => {
        const dealerResourceLists = this.props.detail.dealerResourceLists;
        const {lv2, lv3, lv4} = this.state;
        if(!dealerResourceLists.length) {
            this.setState({
                isSearch: false,
            });
            return;
        }
        if(lv2.length === 0 && lv3.length === 0 && lv4.length === 0) {
            this.setState({
                newDealerResourceLists: dealerResourceLists,
                isSearch: false,
            });
            return;
        }
        let lists = [];
        if(lv2.length > 0)
            lists = dealerResourceLists.filter(v => lv2.includes(v.lV2Code));
        if(lv3.length > 0)
            lists = dealerResourceLists.filter(v => lv3.includes(v.lV3Code));
        if(lv4.length > 0)
            lists = dealerResourceLists.filter(v => lv4.includes(v.lV4Code));
        this.setState({
            newDealerResourceLists: lists,
            isSearch: true
        });
    }
    onChangeCode = (value, name) => {
        this.setState({
            [name]: value
        });
    }
    render() {
        const detailData = this.props.detail || {};
        const {options, dealerResourceLists} = detailData;
        const detailPagination = this.state.detailPagination;
        const isSearch = this.state.isSearch;
        const newDealerResourceLists = this.state.newDealerResourceLists;
        const {formatMessage} = this.props.intl;
        const operations = [];
        if(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(options, PERMISSION.update))
            operations.push(<Button key="update" onClick={this.handleUpdateClick} size="small">{
                formatMessage({
                    id: 'detailPanel.btn.edit',
                    defaultMessage: '编辑'
                })
            }</Button>);
        const columns = [{
            title: formatMessage({
                id: 'detailPanel.column.lV1Code',
                defaultMessage: '品牌编号'
            }),
            dataIndex: 'lV1Code',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.lV1Name',
                defaultMessage: '品牌名称'
            }),
            dataIndex: 'lV1Name',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.lV2Code',
                defaultMessage: '车型代码'
            }),
            dataIndex: 'lV2Code',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.lV2Name',
                defaultMessage: '车型名称'
            }),
            dataIndex: 'lV2Name',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.lV3Code',
                defaultMessage: '版型'
            }),
            dataIndex: 'lV3Code',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.lV4Code',
                defaultMessage: '物料组'
            }),
            dataIndex: 'lV4Code',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.lV4Name',
                defaultMessage: '物料组名称'
            }),
            dataIndex: 'lV4Name',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.productCode',
                defaultMessage: '物料代码'
            }),
            dataIndex: 'productCode',
        },
        {
            title: formatMessage({
                id: 'detailPanel.column.productName',
                defaultMessage: '物料名称'
            }),
            dataIndex: 'productName',
        },
        {
            title: formatMessage({
                id: 'detailPanel.column.kdBomCode',
                defaultMessage: 'KDBOM编号'
            }),
            dataIndex: 'kdBomCode',
        },
        {
            title: formatMessage({
                id: 'detailPanel.column.businessType',
                defaultMessage: '业务类型'
            }),
            dataIndex: 'businessType',
            render: text => conventEnumValueToString(saleOrderBusinessType, text)
        },
        {
            title: formatMessage({
                id: 'detailPanel.column.theoreticalStoreSaleRatio',
                defaultMessage: '理论存销比'
            }),
            dataIndex: 'theoreticalStoreSaleRatio',
        },
        {
            title: formatMessage({
                id: 'detailPanel.column.limitStoreSaleRatioLower',
                defaultMessage: '存销比下限'
            }),
            dataIndex: 'lowerLimitStoreSaleRatio',
        },
        {
            title: formatMessage({
                id: 'detailPanel.column.limitStoreSaleRatioUpper',
                defaultMessage: '存销比上限'
            }),
            dataIndex: 'upperLimitStoreSaleRatio',
        },
        {
            title: formatMessage({
                id: 'detailPanel.column.deliveryCycle',
                defaultMessage: '发货周期'
            }),
            dataIndex: 'deliveryCycle',
        }];
        return (
            <div className="detail">
                <Spin spinning={this.state.loading || this.props.loading}>
                    <Card>
                        <DescriptionList size="large" title={<Row><Col span={12}>{
                            formatMessage({
                                id: 'detailPanel.card.title',
                                defaultMessage: '总代信息'
                            })
                        }</Col>
                        <Col className={`col-align-right ${styles.detail}`} span={12}>{operations}</Col>
                        </Row>}>
                            <Description term={formatMessage({
                                id: 'detailPanel.data.code',
                                defaultMessage: '编号',
                            })}>{this.props.detail.code}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.data.name',
                                defaultMessage: '名称',
                            })}>{this.props.detail.name}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.data.shortCode',
                                defaultMessage: '简码',
                            })}>{this.props.detail.shortCode}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.data.shortName',
                                defaultMessage: '简称',
                            })}>{this.props.detail.shortName}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.data.agentKind',
                                defaultMessage: '客户分类',
                            })}>{conventEnumValueToString(agentKind, this.props.detail.agentKind)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.data.country',
                                defaultMessage: '国家',
                            })}>{this.props.detail.country}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.data.province',
                                defaultMessage: '省份',
                            })}>{this.props.detail.province}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.data.city',
                                defaultMessage: '城市',
                            })}>{this.props.detail.city}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.data.contactNumber',
                                defaultMessage: '联系电话',
                            })}>{this.props.detail.contactNumber}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.data.fax',
                                defaultMessage: '传真',
                            })}>{this.props.detail.fax}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.data.creatorName',
                                defaultMessage: '联系地址',
                            })}>{this.props.detail.creatorName}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.data.zipCode',
                                defaultMessage: '邮政编码',
                            })}>{this.props.detail.zipCode}</Description>
                        </DescriptionList>
                    </Card>
                    <Card
                        title={<div><Row>
                            <Col span={4}>
                                {this.props.intl.formatMessage({
                                    id: 'detailPanel.table.details',
                                    defaultMessage: '可供资源清单'
                                })}
                            </Col></Row>
                        <Row><Col span={6}>
                            <FormItem label={this.props.intl.formatMessage({
                                id: 'detailPanel.operation.lv2',
                                defaultMessage: '车型代码'
                            })}
                            {...FORM_OPTIONS.item}>
                                <TextArea
                                    name="lv2"
                                    value={this.state.lv2}
                                    className={styles.minScreenSearchWidth}
                                    placeholder={formatMessage({
                                        id: 'detailPanel.form.placeholder',
                                        defaultMessage: '多个输入，以回车隔开'
                                    })}
                                    onBlur={this.onChangeCode}/>
                            </FormItem>
                        </Col>
                        <Col span={6}>
                            <FormItem label={this.props.intl.formatMessage({
                                id: 'detailPanel.operation.lv3',
                                defaultMessage: '版型'
                            })}
                            {...FORM_OPTIONS.item}>
                                <TextArea
                                    name="lv3"
                                    value={this.state.lv3}
                                    className={styles.minScreenSearchWidth}
                                    placeholder={formatMessage({
                                        id: 'detailPanel.form.placeholder',
                                        defaultMessage: '多个输入，以回车隔开'
                                    })}
                                    onBlur={this.onChangeCode}/>
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem label={this.props.intl.formatMessage({
                                id: 'detailPanel.operation.lv4Code',
                                defaultMessage: '物料组'
                            })}
                            {...FORM_OPTIONS.item}>
                                <TextArea
                                    name="lv4"
                                    value={this.state.lv4}
                                    className={styles.minScreenSearchWidth}
                                    placeholder={formatMessage({
                                        id: 'detailPanel.form.placeholder',
                                        defaultMessage: '多个输入，以回车隔开'
                                    })}
                                    onBlur={this.onChangeCode}/>
                            </FormItem>
                        </Col>
                        <Col span={4}>
                            <Button className={styles.queryBtn} key="query" type="primary" onClick={this.onSearch} loading={this.state.loading}>
                                {formatMessage({
                                    id: 'queryPanel.btn.query',
                                    defaultMessage: '查询'
                                })}</Button></Col>
                        </Row></div>}>
                        <Table
                            className="white-space-nowrap"
                            columns={columns}
                            rowKey="id"
                            pagination={detailPagination}
                            dataSource={isSearch ? newDealerResourceLists : dealerResourceLists}
                            onChange={this.onChangeDetail}
                            {...TABLE} />

                    </Card>

                </Spin>
                <div className="page-toolbar">
                    <Button
                        type="primary"
                        disabled={this.props.loading || this.state.loading}
                        onClick={this.props.onCancel}>{formatMessage({
                            id: 'detailPanel.btn.return',
                            defaultMessage: '返回'
                        })}</Button>
                </div>
            </div>
        );
    }
}

DetailPanel.propTypes = {
    detail: PropTypes.object.isRequired,
    id: PropTypes.string.isRequired,
    init: PropTypes.func.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    onCancel: PropTypes.func.isRequired,
    history: PropTypes.object,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
    successReturn: PropTypes.func,
};

import {connect} from 'react-redux';
import {getDetail, tableSearch} from './actions';
import {injectIntl} from './intl';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getDetailData = selectorFactory(['page', 'domainData', 'detail', 'data']);
const mapStateToProps = (state, props) => ({
    id: props.id,
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']),
    permissions: getPermissions(state),
    detail: getDetailData(state),
    isDealerUser: state.getIn(['page', 'domainData', 'init', 'isDealerUser']),
});
const mapDispatchToProps = (dispatch, props) => ({
    init: () => dispatch(getDetail(props.id)),
    onCancel: () => {
        props.history.push(routes.query.url());
    },
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(DetailPanel));
